package com.ruoyi.web.controller.talentServerController;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.QQSMSUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TalCirculateTalent;
import com.ruoyi.system.domain.TalTalentInfo;
import com.ruoyi.system.domain.dto.NoticeTalentInfo;
import com.ruoyi.system.service.ITalCirculateTalentService;
import com.ruoyi.system.service.ITalTalentInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TalTalentCirculate;
import com.ruoyi.system.service.ITalTalentCirculateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 人才通知Controller
 *
 * @author zhusq
 * @date 2023-04-04
 */
@RestController
@RequestMapping("/system/circulate")
public class TalTalentCirculateController extends BaseController
{
    @Autowired
    private ITalTalentCirculateService talTalentCirculateService;

    @Autowired
    private ITalCirculateTalentService circulateTalentService ;

    @Autowired
    private ITalTalentInfoService talentInfoService ;



    /**
     * 查询人才流动管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TalTalentCirculate talTalentCirculate)
    {
        startPage();
        List<TalTalentCirculate> list = new ArrayList<>();
        for (SysRole role : SecurityUtils.getLoginUser().getUser().getRoles()) {
            /**数据权限*/
            if (role.getRoleKey().equals("admin") || role.getRoleKey().equals("talent") || role.getRoleKey().equals("teacher")) {
                list = talTalentCirculateService.selectTalTalentCirculateList(talTalentCirculate);
            }else {
                /**普通用户*/
                LambdaQueryWrapper<TalTalentInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TalTalentInfo::getUserId,SecurityUtils.getUserId()) ;
                TalTalentInfo one = this.talentInfoService.getOne(wrapper);
                if (Objects.isNull(one)){
                    throw new ServiceException("你还未申请党员信息！") ;
                }
                Long talentId = one.getId();
                LambdaQueryWrapper<TalCirculateTalent> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TalCirculateTalent::getTalentId,talentId) ;
                List<TalCirculateTalent> circulateTalentList = this.circulateTalentService.list(queryWrapper);
                if (!circulateTalentList.isEmpty()){
                    Map<Long, Integer> map = circulateTalentList.stream().collect(Collectors.toMap(TalCirculateTalent::getCirculateId, TalCirculateTalent::getState));
                    List<Long> longs = new ArrayList<>(map.keySet());
                    LambdaQueryWrapper<TalTalentCirculate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.in(TalTalentCirculate::getId,longs) ;
                    list = talTalentCirculateService.list(lambdaQueryWrapper);
                    LambdaQueryWrapper<TalCirculateTalent> circulateWrapper = new LambdaQueryWrapper<>();
                    for (TalTalentCirculate talentCirculate : list) {
                        circulateWrapper.eq(TalCirculateTalent::getCirculateId,talentCirculate.getId());
                        List<TalCirculateTalent> circulateTalents = circulateTalentService.list(circulateWrapper);
                        LambdaQueryWrapper<TalTalentInfo> talentWrapper = new LambdaQueryWrapper<>();
                        talentWrapper.eq(TalTalentInfo::getUserId,SecurityUtils.getUserId()) ;
                        TalTalentInfo talentInfo = talentInfoService.getOne(talentWrapper);
                        for (TalCirculateTalent circulateTalent : circulateTalents) {
                            if (circulateTalent.getTalentId().equals(talentInfo.getId()) && circulateTalent.getCirculateId().equals(talentCirculate.getId())){
                                talentCirculate.setState(circulateTalent.getState());
                            }
                        }
                        circulateWrapper.clear();
                    }
                }
            }
        }
        for (TalTalentCirculate talentCirculate : list) {
            talentCirculate.setStateDescribe(talentCirculate.getState() == 0 ? "待确认" : "已确认");
        }
        return getDataTable(list);
    }

    /**
     * 导出人才流动管理列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, TalTalentCirculate talTalentCirculate)
    {
        List<TalTalentCirculate> list = talTalentCirculateService.selectTalTalentCirculateList(talTalentCirculate);
        ExcelUtil<TalTalentCirculate> util = new ExcelUtil<TalTalentCirculate>(TalTalentCirculate.class);
        util.exportExcel(response, list, "党员管理数据");
    }

    /**
     * 获取人才流动管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(talTalentCirculateService.selectTalTalentCirculateById(id));
    }

    /**
     * 新增人才流动管理
     */
    @PostMapping
    public AjaxResult add(@RequestBody TalTalentCirculate talTalentCirculate)
    {
        return toAjax(talTalentCirculateService.insertTalTalentCirculate(talTalentCirculate));
    }

    /**
     * 修改人才流动管理
     */
    @PutMapping
    public AjaxResult edit(@RequestBody TalTalentCirculate talTalentCirculate)
    {
        return toAjax(talTalentCirculateService.updateTalTalentCirculate(talTalentCirculate));
    }

    /**
     * 删除人才流动管理
     */
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(talTalentCirculateService.deleteTalTalentCirculateByIds(ids));
    }



    @Autowired
    private ITalTalentInfoService talTalentInfoService;

	/**通知用户*/
    @GetMapping("/noticeTalent")
    public AjaxResult noticeTalent(@RequestParam("talentNoticeId") Long talentNoticeId , @RequestParam("talentList") String talentList){
        if (StringUtils.isBlank(talentList)){
            throw new ServiceException("通知人员信息不能为空！") ;
        }
        TalTalentCirculate circulate = this.talTalentCirculateService.getById(talentNoticeId);
        String content = circulate.getContent();
        String title = circulate.getTitle();
        for (String talentId : talentList.split(",")) {
            TalCirculateTalent talent = new TalCirculateTalent();
            talent.setCirculateId(talentNoticeId);
            talent.setTalentId(Long.valueOf(talentId));
            talent.setCreateTime(new Date());
            try {
                circulateTalentService.insertTalCirculateTalent(talent) ;
                TalTalentInfo one = this.talTalentInfoService.getById(talentId);
                String email = one.getEmail();
                QQSMSUtils.noticeTalentEmail(email,title,content);
            }catch (Exception e){
                logger.info(e.getMessage());
            }
        }
        return success() ;
    }

    @GetMapping("/noticeTalentSuccess")
    public AjaxResult noticeTalentSuccess(@RequestParam("circulateId") Long circulateId){
        LambdaQueryWrapper<TalTalentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TalTalentInfo::getUserId,SecurityUtils.getUserId()) ;
        TalTalentInfo one = this.talentInfoService.getOne(wrapper);
        if (ObjectUtils.isEmpty(one)) {
            throw new ServiceException("您不是当前通知的对象,无法完成该操作!") ;
        }
        Long talentId = one.getId();

        LambdaUpdateWrapper<TalCirculateTalent> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(TalCirculateTalent::getCirculateId,circulateId);
        queryWrapper.eq(TalCirculateTalent::getTalentId,talentId);
        queryWrapper.set(TalCirculateTalent::getState,1) ;
        circulateTalentService.update(queryWrapper);

        LambdaQueryWrapper<TalCirculateTalent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TalCirculateTalent::getCirculateId,circulateId) ;
        List<TalCirculateTalent> list = circulateTalentService.list(lambdaQueryWrapper);
        long count = list.stream().filter((t) -> (t.getState().equals(0))).count();
        if (count == 0L){
            /**全都已经确认完毕*/
            LambdaUpdateWrapper<TalTalentCirculate> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TalTalentCirculate::getId,circulateId) ;
            updateWrapper.set(TalTalentCirculate::getState,1) ;
            this.talTalentCirculateService.update(updateWrapper) ;
        }else {
            LambdaUpdateWrapper<TalTalentCirculate> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TalTalentCirculate::getId,circulateId) ;
            updateWrapper.set(TalTalentCirculate::getState,0) ;
            this.talTalentCirculateService.update(updateWrapper) ;
        }
        return success() ;
    }

    @GetMapping("/getNoticeTalentInfo")
    public List getNoticeTalentInfo(@RequestParam("circulateId") Long circulateId){
        LambdaQueryWrapper<TalCirculateTalent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TalCirculateTalent::getCirculateId,circulateId) ;
        List<TalCirculateTalent> list = circulateTalentService.list(wrapper);
        ArrayList<NoticeTalentInfo> infos = new ArrayList<>();
        for (TalCirculateTalent circulateTalent : list) {
            TalTalentInfo talentInfo = talentInfoService.getById(circulateTalent.getTalentId());
            NoticeTalentInfo info = new NoticeTalentInfo();
            info.setCreateTime(circulateTalent.getCreateTime());
            info.setName(talentInfo.getName());
            info.setPhone(talentInfo.getPhone());
            info.setEmail(talentInfo.getEmail());
            info.setStateDescribe(circulateTalent.getState() == 0 ? "待确认" : "确定收到" );
            infos.add(info) ;
        }
        return infos ;
    }

}
